import axios from 'axios';
import Home from './Home';
import App from './App';
import Preorder from './Preorder';
import { loadingOff } from 'components/Loading';
import * as Sentry from '@sentry/browser';
import qs from 'qs';

require('es6-promise').polyfill(); //  polyfill for IE browser

const axiosIns = axios.create({
    baseURL: APP_CONFIG.appAPI,
});

const token = qs.parse(location.href.split('?')[1]).token || localStorage.apiToken;
if (token) localStorage.apiToken = token;

const apiIns = axios.create({
    baseURL: APP_CONFIG.appServer,
    headers: {
        'Authorization': token
    }
});

axiosIns.interceptors.response.use(handleSuccess, handleError);
apiIns.interceptors.response.use(handleSuccess, handleError);

function handleSuccess (response) {
    // Do something with response data
    loadingOff();

    //  capture backend error
    let { data, status, config } = response;
    
    if (data.code != 0) {
        Sentry.captureException({ data, httpStatus: status, url: config.url }, {});
    }

    return response;
}

function handleError (error) {
    // Do something with request error
    Sentry.captureException(error, {});
    loadingOff();
    return Promise.reject(error);
}

export default {
    Home: Home(axiosIns),
    App: App(axiosIns),
    Preorder: Preorder(apiIns),
    ALL: axiosIns.all,
    API:apiIns
};
